<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/7/8
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper;


use Exception;

class Console
{
    /**
     * @param $argv
     * @return array
     * @throws Exception
     */
    private function buildParams($argv)
    {
        $number = count($argv);
        $params = [];
        for ($i = 0; $i < $number; $i++) {
            if ($argv[$i]{0} == '-') {
                $key          = substr($argv[$i], 1);
                $value        = $argv[++$i] ?? null;
                $params[$key] = $value;
            } else {
                throw new Exception($argv[$i] . "参数格式错误");
            }
        }
        return $params;
    }

    /**
     * @param $command
     * @param $argv
     * @throws Exception
     */
    private function execCommand($command, $argv)
    {
        $params     = $this->buildParams($argv);
        $objectName = '\\paper\\command\\' . ucfirst($command);
        if (!class_exists($objectName)) {
            throw new Exception("此命令不存在");
        }
        $object = new $objectName();
        call_user_func_array([$object, 'exec'], [$params]);
    }

    /**
     * @param array $argv
     * @throws Exception
     */
    public function exec($argv = [])
    {
        array_shift($argv);
        $command = $argv[0] ?? 'help';
        array_shift($argv);
        // echo $command;
        switch ($command) {
            case "init":
                break;
            case "version":
                $msg = "version:0.0.1";
                break;
            case "help":
                $options[] = [
                    'option'      => 'v',
                    'params'      => '',
                    'description' => '显示当前Paper PHP的版本信息',
                ];
                $options[] = [
                    'option'      => 'c',
                    'params'      => '<command>',
                    'description' => '执行command命令',
                ];
                echo "Usage: php command [options]\r\n";
                foreach ($options as $option) {
                    echo "  -{$option['option']}               {$option['description']}\r\n";
                }
                break;
            default:
                $this->execCommand($command, $argv);
                break;
        }
    }
}